package com.cloud.user.biz.login.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.excption.BizException;
import com.cloud.mall.user.TbMember;
import com.cloud.user.biz.dto.LoginDto;
import com.cloud.user.biz.dto.LoginType;
import com.cloud.user.biz.login.AbstractLogin;
import com.cloud.user.service.ITbMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * @Author tangyuan2meicloud.com
 * @DATE 2021/7/7 11:41
 * @Desc
 * @Remarks
 */

/**
 * 手机验证码登录
 */
@Service
public class PhoneNumberAndCodeLogin extends AbstractLogin {

    @Autowired
    private ITbMemberService iTbMemberService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Integer getLoginType() {
        return LoginType.PHONE_CODE.getCode();
    }

    @Override
    public TbMember validate(LoginDto authLoginDto) {
//        手机验证码
        String phone = authLoginDto.getPhone();
        String code = authLoginDto.getCode();
        if (phone == null || code == null) {
            throw new BizException("手机或者验证码不存在");
        }

        if (!StringUtils.hasLength(phone) || !StringUtils.hasLength(code)) {
            throw new BizException("500", "手机号和密码不能为空");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", phone);
        List<TbMember> list = iTbMemberService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            throw new BizException("500", "账号不存在");
        }
        TbMember tbMember = list.get(0);
        String s = redisTemplate.opsForValue().get(phone);
        if (s == null) {
            throw new BizException("500", "验证码过期或者未发送");
        }

        if (s != null && Objects.equals(s, code)) {
            redisTemplate.delete(phone);
            return tbMember;
        }
        throw new BizException("500", "验证码错误");
    }

    @Override
    public TbMember doProcessor(LoginDto authLoginDto) {
        return null;
    }
}
